#include "burn.h"

uint32_t burnIndex;
void burn_reset(void)
{
    FLASH_SetLatency(FLASH_Latency_15);
    burnIndex = 0;
}

void burn_writePack(unsigned char *buffer, unsigned int bufferLen)
{
    flash_write(buffer, bufferLen, burnIndex+APP_FLASH_ADDRESS);
    burnIndex += bufferLen;
}
void burn_end(void)
{
    Burn_Parameters parm;
    FLASH_SetLatency(FLASH_Latency_2);
    burn_parameters_read(&parm);
    parm.firmwareSize = burnIndex;
    burn_parameters_write(&parm);
}

void burn_parameters_write(Burn_Parameters *writeParm)
{
    uint32_t tmp;
    uint32_t address;
    FLASH_Unlock();
    FLASH_ErasePage(APP_PARAMETERS_ADDR);
    //写CRC
    address = APP_PARAMETERS_ADDR;
    tmp = 0;
    tmp |= writeParm->crc;
    FLASH_ProgramWord(address, tmp);
    //写整包长度
    address+=4;
    tmp = 0;
    tmp |= writeParm->firmwareSize;
    FLASH_ProgramWord(address, tmp);
    FLASH_Lock();
}
void burn_parameters_read(Burn_Parameters *readParm)
{
    uint32_t *address;
    address = (uint32_t *)APP_PARAMETERS_ADDR;
    readParm->crc = (uint16_t)*address;
    address+=1;
    readParm->firmwareSize = *address;
}

void burn_write_crc(uint16_t crc)
{
    Burn_Parameters parm;
    burn_parameters_read(&parm);
    parm.crc = crc;
    burn_parameters_write(&parm);
}
